package com.leidi.javacallspython.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class LabelUtil {
	public static JSONArray setEnumType(Class<?> clasz){
		JSONArray jsonArray = new JSONArray();
		Object[] enumConstants = clasz.getEnumConstants();
		try {
			Method getLabel = clasz.getMethod("getLabel");
			Method getValue = clasz.getMethod("getValue");
			for (Object enumConstant : enumConstants) {
				JSONObject obj = new JSONObject();
				String label = String.valueOf(getLabel.invoke(enumConstant));
				String value = String.valueOf(getValue.invoke(enumConstant));
				obj.put("label", label);
				obj.put("value", value);
				jsonArray.add(obj);
			}
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return jsonArray;
	}

	public static List<Map<String, String>> converObjectList(List<?> objData, Class<?> clazz){
		String className = "";
		String name = clazz.getSimpleName();
		if ("SysUser".equals(name)){
			className = "User";
		} else {
			className = name;
		}
		List<Map<String, String>> collect = null;
		try {
			Method getId = clazz.getMethod("get" + className + "Id");
			Method getName = clazz.getMethod("get" + className + "Name");
			collect = objData.stream().map(i -> {
				Map<String, String> map = new HashMap<>();
				try {
					map.put("value", String.valueOf(getId.invoke(i)));
					map.put("label", String.valueOf(getName.invoke(i)));
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
				return map;
			}).collect(Collectors.toList());
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		return collect;
	}
}
